package org.example.leetcode.addon.lc107;

import org.example.util.TreeNode;

import java.util.*;

public class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        if (root == null) {
            return Collections.EMPTY_LIST;
        }
        List<List<Integer>> ans = new LinkedList<>();
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            List<Integer> floor = new LinkedList<>();
            int size = queue.size();

            for (int i = size; i > 0; i--) {
                TreeNode node = queue.poll();
                floor.add(node.val);

                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }

            ans.add(floor);
        }

        Collections.reverse(ans);
        return ans;
    }

    public static void main(String[] args) {

    }
}
